package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.RuYiHuaApiBUtil;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 如意花 APIB回调
 */
@Service
public class RuYiHuaApiBPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;
    @Autowired
    IApplicationInfoService applicationInfoService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String channelCode = pushApiKeyParam.getApiCode();
        String apiSecret = pushApiKeyParam.getApiSecret();
        String requestId = UUID.randomUUID().toString().replace("-", "");
        String mobileMd5 = memberSourceInfo.getMobileMd5().toLowerCase();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phoneMd5", mobileMd5);
        bizMap.put("realName", memberSourceInfo.getRealname());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("gender", RuYiHuaApiBUtil.getGender(memberSourceInfo.getSex()));
        bizMap.put("workCity", memberSourceInfo.getCity());
        bizMap.put("cityCode", memberSourceInfo.getCityCode());
        bizMap.put("accumulationFund", RuYiHuaApiBUtil.getFund(memberSourceInfo.getGjj()));
        bizMap.put("socialSecurity", RuYiHuaApiBUtil.getShebao(memberSourceInfo.getShebao()));
        bizMap.put("house", RuYiHuaApiBUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("vehicle", RuYiHuaApiBUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("insurance", RuYiHuaApiBUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        bizMap.put("sesameScore", RuYiHuaApiBUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("professional", RuYiHuaApiBUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("ip", RuYiHuaApiBUtil.getIp(memberSourceInfo.getReqIp()));
        bizMap.put("client", 1);
        bizMap.put("amount", RuYiHuaApiBUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTerm", RuYiHuaApiBUtil.getLoanTerm(memberSourceInfo.getLoanTime()));
        bizMap.put("loanUse", RuYiHuaApiBUtil.getYongtu(memberSourceInfo.getYongtu()));
        bizMap.put("creditCard", RuYiHuaApiBUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        bizMap.put("huabei", RuYiHuaApiBUtil.getHuaBei(memberSourceInfo.getHuabei()));
        bizMap.put("baitiao", RuYiHuaApiBUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        bizMap.put("monthIncome", RuYiHuaApiBUtil.getShouRu(memberSourceInfo.getShouru()));
        bizMap.put("salaryType", 1);
        bizMap.put("education", RuYiHuaApiBUtil.getXueLi(memberSourceInfo.getXueli()));

        //加密
        String encrypt = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("content",encrypt);
        paramMap.put("requestId",requestId);
        paramMap.put("channelCode",channelCode);
        paramMap.put("requestTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        log.info("【如意花下游APIB半流程】撞库开始【queryUrl】{}【bizMap】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        JSONObject resultObject = JSON.parseObject(result);

        log.info("【如意花下游APIB半流程】撞库结束【resultDes】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code),"200")) {
            pushApiResult.setPushSuccess(true);

            JSONObject data = resultObject.getJSONObject("data");
            String applyNo = data.getString("applyNo");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("applyNo",applyNo);
            pushApiResult.setExtJson(jsonObject);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String channelCode = pushApiKeyParam.getApiCode();
        String requestId = UUID.randomUUID().toString().replace("-", "");
        String apiSecret = pushApiKeyParam.getApiSecret();
        String applyNo = extJson.getString("applyNo");
        String mobile = memberSourceInfo.getMobile();

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("applyNo", applyNo);
        bizMap.put("mobile", mobile);
        bizMap.put("realName", memberSourceInfo.getRealname());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("gender", RuYiHuaApiBUtil.getGender(memberSourceInfo.getSex()));
        bizMap.put("workCity", memberSourceInfo.getCity());
        bizMap.put("cityCode", memberSourceInfo.getCityCode());
        bizMap.put("accumulationFund", RuYiHuaApiBUtil.getFund(memberSourceInfo.getGjj()));
        bizMap.put("socialSecurity", RuYiHuaApiBUtil.getShebao(memberSourceInfo.getShebao()));
        bizMap.put("house", RuYiHuaApiBUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("vehicle", RuYiHuaApiBUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("insurance", RuYiHuaApiBUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        bizMap.put("sesameScore", RuYiHuaApiBUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("professional", RuYiHuaApiBUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("ip", RuYiHuaApiBUtil.getIp(memberSourceInfo.getReqIp()));
        bizMap.put("client", 1);
        bizMap.put("amount", RuYiHuaApiBUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        bizMap.put("loanTerm", RuYiHuaApiBUtil.getLoanTerm(memberSourceInfo.getLoanTime()));
        bizMap.put("loanUse", RuYiHuaApiBUtil.getYongtu(memberSourceInfo.getYongtu()));
        bizMap.put("creditCard", RuYiHuaApiBUtil.getXinYongKa(memberSourceInfo.getXinyongka()));
        bizMap.put("huabei", RuYiHuaApiBUtil.getHuaBei(memberSourceInfo.getHuabei()));
        bizMap.put("baitiao", RuYiHuaApiBUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        bizMap.put("monthIncome", RuYiHuaApiBUtil.getShouRu(memberSourceInfo.getShouru()));
        bizMap.put("salaryType", 1);
        bizMap.put("education", RuYiHuaApiBUtil.getXueLi(memberSourceInfo.getXueli()));

        //加密
        String encrypt = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("content",encrypt);
        paramMap.put("requestId",requestId);
        paramMap.put("channelCode",channelCode);
        paramMap.put("requestTime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        log.info("【如意花下游APIB半流程】导单开始【queryUrl】{}【bizMap】{}【paramMap】{}", requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();

        JSONObject resultObject = JSON.parseObject(result);

        log.info("【如意花下游APIB半流程】导单结束【result】{}", resultObject.toJSONString());

        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("message");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code),"200")) {
            JSONObject jsonObject1 = resultObject.getJSONObject("data");
            String url1 = jsonObject1.getString("url");
            pushApiResult.setApproveUrl(url1);
            pushApiResult.setOutOrderNo(applyNo);
            pushApiResult.setPushSuccess(true);
            return pushApiResult;
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
        noticeParamDTO.setQueryResult(paramContent);

        JSONObject jsonObject = JSON.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObject)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }
        Integer status = jsonObject.getInteger("status");
        if (status != 1){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }
        String orderNo = jsonObject.getString("applyNo");
        noticeParamDTO.setOutOrderNo(orderNo);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(orderNo));

        if (ObjectUtil.isEmpty(entityByOutOrderNoLock) || PushStatusEnum.SUCCESS.getValue().equals(entityByOutOrderNoLock.getStatus())){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
        }

        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("msg","成功");
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

}
